/**
 * Copyright (c) 2010 Abadi Kurniawan, Brian Dukes
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE 
 * USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package hackathon.android.mymessageinbox;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

/**
 * @author Abadi Kurniawan, Brian Dukes
 *
 */
public class LoginActivity extends Activity {
	private String userName;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
    	
    	setContentView(R.layout.login);

    	Button loginButton = (Button)findViewById(R.id.login_button);
    	loginButton.setOnClickListener(new OnClickListener() {
    		public void onClick(View v)
    		{
    			userName = ((EditText)findViewById(R.id.txt_username)).getText().toString();
    			String password = ((EditText)findViewById(R.id.txt_password)).getText().toString();
    			
    			Log.d("Engage", "[Username:"+userName+"],[Password:"+password+"]");
    			
    			Intent serviceIntent = new Intent(LoginActivity.this, LoginService.class);
    			serviceIntent.putExtra(LoginService.EXTRA_USER_NAME, userName);
    			serviceIntent.putExtra(LoginService.EXTRA_PASSWORD, password);
    			
    	        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(LoginActivity.this);
    	        String webServiceUrl = prefs.getString(getString(R.string.settings_url_name), "");
    			serviceIntent.putExtra(LoginService.EXTRA_WEB_SERVICE_URL, webServiceUrl);
    			
    			registerReceiver(new LoginReceiver(), new IntentFilter(MessageService.INTENT_AUTHENTICATION));
    			startService(serviceIntent);
    		}
    	});
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
    	MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.login_menu, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
        case R.id.menu_settings:
        	settings();
        	return true;
        case R.id.menu_quit:
        	quit();
        	return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
    
    public void settings()
    {
    	Intent settingsActivity = new Intent(getBaseContext(),
    			Preferences.class);
    	startActivity(settingsActivity);
    }
    
    private void quit()
    {
    	new AlertDialog.Builder(this)
        .setIcon(android.R.drawable.ic_dialog_alert)
        .setTitle(R.string.quit)
        .setMessage(R.string.really_quit)
        .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

                //Stop the activity
                LoginActivity.this.finish();    
            }
        })
        .setNegativeButton(R.string.no, null)
        .show();
    }
    
    /**
     * Receiver for LoginService broadcast messages.
     * @author Abadi Kurniawan, Brian Dukes
     *
     */
    private class LoginReceiver extends BroadcastReceiver
    {
		@Override
		public void onReceive(Context context, Intent intent) {
			
			Bundle bundle = intent.getExtras();
			if(bundle != null)
			{
				String result = bundle.getString(MessageService.EXTRA_AUTHENTICATION);				
				String token;
				try {
					JSONObject json = new JSONObject(result);
					token = json.getString("Token");
					Log.d("Engage","[Token:"+token+"]");
					Intent main = new Intent();
					main.setClass(LoginActivity.this, MyMessage.class);
					main.putExtra(MyService.EXTRA_TOKEN, token);    			
					main.putExtra(MyService.EXTRA_USERNAME, userName);
					startActivity(main);
					LoginActivity.this.finish();
				} catch (JSONException e) {
					e.printStackTrace();
					new AlertDialog.Builder(LoginActivity.this)
			        .setIcon(android.R.drawable.ic_dialog_alert)
			        .setTitle(R.string.login)
			        .setMessage(R.string.login_failed)
			        .setPositiveButton(R.string.ok, null)
			        .show();
				}
			}
			unregisterReceiver(this);
			stopService(new Intent(LoginActivity.this, LoginService.class));
		}
    	
    }
}
